﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Collections.Specialized;
using System.Web;
using System.Xml.Linq;


namespace Twi.COMMON.WCF
{
    public class HttpHelper
    {
        public static string QueryString(string key)
        {
            try
            {
                if (OperationContext.Current == null || OperationContext.Current.RequestContext == null)
                {
                    return "服务端自请求";  //服务端自己调用自己
                }

                //获得用户请求信息
                var request = OperationContext.Current.RequestContext.RequestMessage;

                if (request.State == MessageState.Closed)
                {
                    return "Http请求已关闭";
                }

                // 获得Http请求
                var requestProp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

                // 获取字符
                NameValueCollection queryParams = HttpUtility.ParseQueryString(requestProp.QueryString);

                //返回
                if (queryParams.AllKeys.Contains(key))
                {
                    return queryParams[key] ?? "";
                }
                else
                {
                    if (key == "version")
                    {
                        return "其他请求";  
                    }
                    return "";
                }
            }
            catch(Exception ex)
            {
                throw new Exception("key:" + key + Environment.NewLine + ex.GetFullMessage());
            }
        }

        public static int QueryUid() 
        {
            return int.Parse(QueryString("uid"));
        }

        public static string QueryUname() 
        {
            return QueryString("uname");
        }

        /// <summary>
        /// 用户类型
        /// </summary>
        /// <returns>1: 普通用户; 2:管理员</returns>
        public static int QueryUserType()
        {
            if (!string.IsNullOrEmpty(QueryString("utype")))
                return int.Parse(QueryString("utype"));
            else
                return 1;
        }

        #region 用户HTTP请求部分的相关信息




        /// <summary>
        /// 返回指定的服务器变量信息
        /// </summary>
        /// <param name="strName">服务器变量名</param>
        /// <returns>服务器变量信息</returns>
        public static string GetServerString(string strName)
        {
            if (HttpContext.Current.Request.ServerVariables[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.ServerVariables[strName].ToString();
        }

        /// <summary>
        /// 以xml格式返回所有服务器变量信息
        /// </summary>
        /// <returns></returns>
        public static System.Xml.Linq.XElement GetServerXmlString()
        {
            System.Xml.Linq.XElement xeClient = new System.Xml.Linq.XElement("ClientHttpRequestInfo");

            foreach (string key in HttpContext.Current.Request.ServerVariables.AllKeys)
            {
                xeClient.SetElementValue(key, HttpContext.Current.Request.ServerVariables[key].ToString());
            }

            return xeClient;
        }


        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            if (!request.Url.IsDefaultPort)
            {
                return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
            }
            return request.Url.Host;
        }

        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }


        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }

        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public static bool IsBrowserGet()
        {
            string[] BrowserName = { "ie", "opera", "netscape", "mozilla", "konqueror", "firefox" };
            string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < BrowserName.Length; i++)
            {
                if (curBrowser.IndexOf(BrowserName[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获得当前完整Url地址
        /// </summary>
        /// <returns>当前完整Url地址</returns>
        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }
        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.QueryString[strName];
        }

        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1].ToLower();
        }
        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetProxyIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (null == result || result == String.Empty || !Utils.IsIP(result))
            {
                return "0.0.0.0";
            }

            return result;

        }


        public static string GetIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (null == result || result == String.Empty || !Utils.IsIP(result))
            {
                return "0.0.0.0";
            }

            return result;

        }

        /// <summary>
        /// 获取计算机的登录用户帐号
        /// </summary>
        /// <returns></returns>
        public static string GetLogonUser()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["LOGON_USER"];

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_USER"];
            }

            if (null == result || result == String.Empty)
            {
                return "";
            }

            return result;
        }


        #endregion

        #region 设置请求属性
        /// <summary>
        /// 设置请求属性
        /// </summary>
        /// <param name="name">属性名称</param>
        /// <param name="property">属性值</param>
        public static void SetRequestProperty(string name, object property)
        {
            //获得用户请求信息
            var request = OperationContext.Current.RequestContext.RequestMessage;

            if (request.State == MessageState.Closed)
            {
                return;
                // return "Http请求已关闭";
            }
           
            var poperties = request.Properties.Where(x => x.Key == name);
            if ((poperties == null || poperties.Count() < 1) )
            {
                if (property != null)
                {
                    request.Properties.Add(name, property);
                }
            }
            else
            {
                request.Properties[name] = property;
            }
        }
        #endregion

        #region 获取请求属性值
        /// <summary>
        /// 获取请求属性值
        /// </summary>
        /// <param name="name">属性名称</param>
        /// <returns>属性值</returns>
        public static object GetRequestProperty(string name, bool getFromQueryWhenNull=false)
        {
            //获得用户请求信息
            var request = OperationContext.Current.RequestContext.RequestMessage;

            if (request.State == MessageState.Closed)
            {
                return null;
                // return "Http请求已关闭";
            }
            var poperties = request.Properties.Where(x => x.Key == name);
            if (poperties != null && poperties.Count()>0)
            {
               return request.Properties[name];
            }
            return null;
        }
        #endregion

    
    }
}
